package zheezes.swt.databinding;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import org.eclipse.core.databinding.BindingException;

final class CalssUtil {
	private static final Object[] EMPTY_ARRAY = new Object[0];

	public static Method getMethod(Class<?> clazz, String propertyName) {
		if (propertyName != null) {
			PropertyDescriptor descriptor = getPropertyDescriptor(clazz,
					propertyName);
			if (descriptor != null) {
				return descriptor.getReadMethod();
			}
		}
		return null;
	}

	public static Object invokeMethod(Method method, Class<?> clazz,
			Object element) {
		if (method != null && instanceOf(clazz, element)) {
			try {
				return method.invoke(element, EMPTY_ARRAY);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return null;
	}

	public static boolean instanceOf(Class<?> clazz, Object element) {
		return element != null && clazz.isAssignableFrom(element.getClass());
	}

	private static PropertyDescriptor getPropertyDescriptor(Class<?> clazz,
			String propertyName) {
		BeanInfo beanInfo;
		try {
			beanInfo = Introspector.getBeanInfo(clazz);
		} catch (IntrospectionException e) {
			return null;
		}
		PropertyDescriptor[] propertyDescriptors = beanInfo
				.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			if (descriptor.getName().equals(propertyName)) {
				return descriptor;
			}
		}
		throw new BindingException("Could not find property with name "	+ propertyName + " in class " + clazz);
	}
}